var agreementFilter = function (options) {
    var _options = options;
    var $ = grp.jQuery;
    function init() {
        filterAgreements(_options.client ? _options.client : $("select[name=client]").val());
        $("select[name=client]").change(function () {
            filterAgreements($(this).val());
        });
        var oldDismiss = dismissAddAnotherPopup;
        dismissAddAnotherPopup = function (win) {
            oldDismiss.apply(this, arguments);
            var select = $("#" + windowname_to_id(win.name));
            if (select.is("[name=agreement]"))
                filterAgreements($("select[name=client]").val());
        };
    }

    function filterAgreements(client) {
        var select = $("select[name=agreement]");
        if (select.length == 0) return;
        if (client) {
            $.ajax({
                method: "POST",
                url: _options.url.replace("/0/", "/" + client + "/"),
                data: {csrfmiddlewaretoken: $.cookie('csrftoken')},
                async: false
            }).done(bindOptions);
        }
        else {
            select.empty();
            select.append($("<option value>---------</option>"));
        }
    }

    function bindOptions(options) {
        var select = $("select[name=agreement]");
        var selected = select.val();
        select.empty();
        select.append($("<option value>---------</option>"));
        $.each(options, function (i, value) {
            select.append($("<option></option>")
                .attr("value", value.id).text(value.number));
        });
        select.val(selected);
    }

    init();
}